package cn.ictgu.parse.crawler;

import cn.ictgu.dto.VideoInfo;
import cn.ictgu.dao.model.Juji;
import cn.ictgu.parse.VideoParse;
import cn.ictgu.tools.JsoupUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 乐视视频解析
 * Created by Silence on 2017/1/7.
 */
public class Letv extends VideoParse{

  private final static String LETV = "乐视视频";

  private final static String cookie = "ark_uuid=d966d5301be94c5bb8fae78b9cd3038e; vjuids=-8a183d9b7.157666171cd.0.43147ea3e2342; OUTFOX_SEARCH_USER_ID_NCOO=410937176.92591244; _search=%E7%88%B5%E8%BF%B9%2C%E5%85%B0%E9%99%B5%E7%8E%8B%E5%A6%83%2C%E5%98%BF%E5%AD%A9%E5%AD%90; tj2_lc=c9b56fa67fdcfb1a73c5fa08ac1cb90f; lb_live_c=105; leBlockOrder=8310%2C8526%2C8527%2C8313%2C8314%2C8315%2C8316%2C8317%2C8318%2C8319%2C8320%2C9471%2C8321%2C8322%2C8323%2C8324%2C8325%2C8326%2C8327%2C8328%2C8329%2C8330; m=qq_A885BF17CA7730A088264FC3871849BC; sso_tk=1024c58894RQg3ZjVlQNpJ6dtd5O6JwC0ilhuH2o87PSH5HP4qw6ez9FB8uKfYem2J8prLzSQ; sso_nickname=%E6%85%95%E5%90%8D%E8%80%8C%E6%9D%A5_221; casflag=1; ssouid=158449217; sso_picture=https%3A%2F%2Fi1.letvimg.com%2Flc05_user%2F201601%2F06%2F15%2F14%2F14520644591333_70_70.jpg; sso_icon=https%3A%2F%2Fi1.letvimg.com%2Flc05_user%2F201601%2F06%2F15%2F14%2F14520644591333_298_298.jpg%2Chttps%3A%2F%2Fi1.letvimg.com%2Flc05_user%2F201601%2F06%2F15%2F14%2F14520644591333_200_200.jpg%2Chttps%3A%2F%2Fi1.letvimg.com%2Flc05_user%2F201601%2F06%2F15%2F14%2F14520644591333_70_70.jpg%2Chttps%3A%2F%2Fi1.letvimg.com%2Flc05_user%2F201601%2F06%2F15%2F14%2F14520644591333_50_50.jpg; utype=3; lfrom=my; u=eyJ1aWQiOiIxNTg0NDkyMTciLCJuaWNrbmFtZSI6Ilx1NjE1NVx1NTQwZFx1ODAwY1x1Njc2NV8yMjEiLCJlbWFpbCI6IiIsIm5hbWUiOiJxcV9BODg1QkYxN0NBNzczMEEwODgyNjRGQzM4NzE4NDlCQyIsInNzb3VpZCI6IjE1ODQ0OTIxNyJ9; ui=d47eMfxBXSFB3kioJDib8y62jf62DFwWYkGxlw%2FvXWJgezXTlFIBqRMPHnFYWiQ6YuxWMnHGF%2BN52O2pCVTUTSrnaDmApLsyZVbB03gatH0dMlWamzZl6U5C4AZJuN%2BJ5aYGH4q0B%2B6NxsqlAcLWKpQ%2FuX9dd2fhz8KEkqIxfDhh62lWgsqMqwC5Jtkq1LrHGtpQbknbfXpEHbCcgWAO6R3baH11eU4; currentLeft_miniPlayer=825; currentTop_miniPlayer=335; vjs-supportM3U8=0; tj_env=1; bd_xid=178D3CF87F892133E76A7BBEB78C903E70564321; csrf=b8031c0563632b536b6b; sso_curr_country=CN; language=zh-cn; tj_uuid=14870784796669555567; logInPlayTime=1; newVideo=%7B%221%22%3A17%2C%222%22%3A111%2C%223%22%3A129%2C%224%22%3A733%2C%225%22%3A6%2C%228%22%3A0%2C%229%22%3A49%2C%2211%22%3A84%2C%2214%22%3A20%2C%2216%22%3A6%2C%2217%22%3A0%2C%2219%22%3A0%2C%2220%22%3A17%2C%2222%22%3A43%2C%2223%22%3A11%2C%2230%22%3A3523%2C%2232%22%3A0%2C%2233%22%3A0%2C%2234%22%3A0%2C%2235%22%3A0%2C%2236%22%3A2%2C%2238%22%3A0%2C%2239%22%3A10%2C%2240%22%3A0%2C%2242%22%3A0%2C%2243%22%3A1%2C%2245%22%3A24%2C%2246%22%3A0%2C%2247%22%3A0%2C%2248%22%3A0%2C%2249%22%3A0%2C%2250%22%3A0%2C%2251%22%3A0%2C%2252%22%3A0%2C%2253%22%3A0%2C%2254%22%3A0%2C%2255%22%3A0%2C%2260%22%3A0%2C%2261%22%3A0%2C%22200%22%3A0%2C%22333%22%3A0%2C%221009%22%3A1760%2C%221021%22%3A120%2C%221029%22%3A35%2C%221035%22%3A0%7D; lang=zh_cn; geo=CN_9_126_1; fe_uv=1; ___rl__test__cookies=1487078799343; _gat=1; his_vid=27639161-27640281-27639052-27538183-27590042-27611682-27611675-27611667-27611880-27611878; tj_v2c=-27639052_2; _ga=GA1.2.15673798.1487080015; tj_lc=178D3CF87F892133E76A7BBEB78C903E70564321; vjlast=1474891445.1487078481.11; autoOpenApp=2";

  private final static String ROUTE = "http://player.pc.le.com/mms/out/video/playJson.json?platid=3&splatid=301&tss=no&id=%s&detect=0&dvtype=1000&accessyx=1&domain=undefined&tkey=%s&devid=178D3CF87F892133E76A7BBEB78C903E70564321&source=1001&lang=cn&region=cn&isHttps=0";
  private final static String VIP_LOCATION = "%s%s&uid=158449217&format=1&jsonp=vjs_148707879345211&expect=3&p1=0&p2=04&termid=2&ostype=un&hwtype=iphone&uuid=1169521875962237&vid=%s";
  private final static String LE_PAGE = "http://m.le.com/vplay_%s.html";
  private static final String LETV_VIDEOS = "http://d.api.m.le.com/apipccard/dynamic?cid=2&vid=%s&platform=pc&isvip=1&type=episode,Cotherlist";

  private final static String TITLE_REGX = "\"title\":\"(.*?)\"";
  private final static String VID_REGX = "([0-9]+)\\.html";

  @Override
  public VideoInfo parseVideoFromUrl(String videoUrl) {
    VideoInfo videoInfo = createVideoInfoWithCopyRight(LETV, videoUrl, "Github", "http://github.com");
    videoInfo.setType("NORMAL");
    String vid = this.matchVid(videoUrl);
    String url = String.format(LE_PAGE, vid);
    Document document = getDocument(url);
    String html = document.html();
    Matcher titleMatcher = Pattern.compile(TITLE_REGX).matcher(html);
    if (titleMatcher.find()){
      videoInfo.setTitle(titleMatcher.group(1));
    }
    String routeUrl = String.format(ROUTE, vid, getTkey());
    document = getDocument(routeUrl, cookie);
    JSONObject object = JSONObject.parseObject(document.text());
    String domain = object.getJSONObject("msgs").getJSONObject("playurl").getJSONArray("domain").getString(0);
    String dispatch = object.getJSONObject("msgs").getJSONObject("playurl").getJSONObject("dispatch").getJSONArray("1300").getString(0);
    String locationUrl = String.format(VIP_LOCATION, domain, dispatch, vid);
    Document result = getDocument(locationUrl);
    String text = StringEscapeUtils.unescapeJava(result.text());
    text = text.replace("vjs_148707879345211(","");
    text = text.replace(");","");
    JSONObject videoJson = JSONObject.parseObject(text);
    videoInfo.setPlayUrl(videoJson.getJSONArray("nodelist").getJSONObject(0).getString("location"));
    return videoInfo;
  }

  @Override
  public List<Juji> parseJujiFromUrl(String videoUrl) {
    List<Juji> jujis = new ArrayList<>();
    Document document = getDocument(videoUrl);
    Matcher matcher = Pattern.compile("([0-9]{5,})\\.html").matcher(document.html());
    if (matcher.find()) {
      String vid = matcher.group(1);
      String videosAPI = String.format(LETV_VIDEOS, vid);
      String data = getDocument(videosAPI).body().text();
      JSONObject jsonObject = JSONObject.parseObject(data);
      JSONArray array = jsonObject.getJSONObject("data").getJSONObject("episode").getJSONArray("videolist");
      if (array.size()>1){
        for (int i = array.size() - 1; i >= 0; i--) {
          JSONObject object = array.getJSONObject(i);
          Juji juji = new Juji();
          Integer index = object.getInteger("episode");
          if (index < 10) {
            juji.setIndex("0" + index);
          } else {
            juji.setIndex("" + index);
          }
          juji.setValue(object.getString("url"));
          jujis.add(juji);
        }
      }
    }
    return jujis;
  }

  private String matchVid(String videoUrl){
    Matcher matcher = Pattern.compile(VID_REGX).matcher(videoUrl);
    if (matcher.find()){
      return matcher.group(1);
    }else {
      Document realDocument = JsoupUtils.getDocWithPC(videoUrl);
      matcher = Pattern.compile("vid:\"(.*?)\"").matcher(realDocument.html());
      if (matcher.find())
        return matcher.group(1);
    }
    return "";
  }

  //乐视tkey算法
  private static String getTkey() {
    int a = (int) (new Date().getTime() / 1000);
    for (int i = 0; i < 8; i++) {
      int b = a >> 1;
      int c = (0x1 & a) << 31;
      a = b + c;
    }
    int result = 0xB074319 ^ a;
    return "" + result;
  }

}
